/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ib.algokit.forex;

import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

import com.ib.algokit.history.StopLossClosedEvent;

/**
 *
 * @author dmisev
 */
public class StopLossClosedEventAvgAltChangeHash {
	private TreeMap<Double, StopLossClosedEvent> cache = new TreeMap<Double, StopLossClosedEvent>();
	
	public StopLossClosedEventAvgAltChangeHash(List<StopLossClosedEvent> stopLossClosedEvents) {
		cache.clear();
		for(StopLossClosedEvent stopLossClosedEvent: stopLossClosedEvents) {
			ForexPairStates forexPairStates=stopLossClosedEvent.getForexPairStates();
			double altPercChange=forexPairStates.getAverageAlternativePercChange();
			StopLossClosedEvent prevStopLossClosedEvent=cache.put(altPercChange, stopLossClosedEvent);
			boolean hasUniqueKey=prevStopLossClosedEvent==null;
			while(!hasUniqueKey){
				altPercChange+=1.0E-10;
				if(!cache.containsKey(altPercChange)){
					if(cache.put(altPercChange, prevStopLossClosedEvent)!=null){
						throw new RuntimeException("shouldn't happen avgAltPercChange exists "+altPercChange);
					}
					hasUniqueKey=true;
				}
			}
			
		}
	}
	
	public List<StopLossClosedEvent> getInterval(Double start, Double end) {        
	    SortedMap<Double, StopLossClosedEvent> subMap = cache.subMap(start, end);
	    List<StopLossClosedEvent> results = new ArrayList<StopLossClosedEvent>();
	    results.addAll(subMap.values());        
	    return results;
	}
}